<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是内核定时器基础知识的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV10-05-内核定时器-01-基础知识">
<meta property="og:url" content="https://sumumm.github.io/post/382dea03.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是内核定时器基础知识的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV10-05-%E5%86%85%E6%A0%B8%E5%AE%9A%E6%97%B6%E5%99%A8-01-%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/img/image-20220918154908163.png">
<meta property="article:published_time" content="2023-07-08T10:58:25.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:57.004Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV10-驱动开发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV10-05-%E5%86%85%E6%A0%B8%E5%AE%9A%E6%97%B6%E5%99%A8-01-%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/img/image-20220918154908163.png">


<link rel="canonical" href="https://sumumm.github.io/post/382dea03.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/382dea03.html","path":"post/382dea03.html","title":"LV10-05-内核定时器-01-基础知识"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV10-05-内核定时器-01-基础知识 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%86%85%E6%A0%B8%E6%97%B6%E9%97%B4%E7%AE%A1%E7%90%86"><span class="nav-text">一、内核时间管理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E8%8A%82%E6%8B%8D%E7%8E%87%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-text">1. 节拍率是什么？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%8A%82%E6%8B%8D%E7%8E%87%E7%9A%84%E9%AB%98%E4%BD%8E%E5%BD%B1%E5%93%8D"><span class="nav-text">2. 节拍率的高低影响</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-jiffies"><span class="nav-text">3. jiffies</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C%E8%B6%85%E6%97%B6%E5%88%A4%E6%96%AD"><span class="nav-text">4. 代码执行超时判断</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%BB%B6%E6%97%B6%E6%9C%BA%E5%88%B6"><span class="nav-text">二、延时机制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%BF%99%E7%AD%89%E5%BE%85%E7%9A%84%E7%9F%AD%E5%BB%B6%E8%BF%9F"><span class="nav-text">1. 忙等待的短延迟</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%BF%99%E7%AD%89%E5%BE%85%E7%9A%84%E9%95%BF%E5%BB%B6%E6%97%B6"><span class="nav-text">2. 忙等待的长延时</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%9D%A1%E7%9C%A0%E5%BB%B6%E6%97%B6"><span class="nav-text">3. 睡眠延时</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E5%BB%B6%E6%97%B6%E6%9C%BA%E5%88%B6%E7%9A%84%E9%80%89%E6%8B%A9"><span class="nav-text">4. 延时机制的选择</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-%E6%89%A7%E8%A1%8C%E6%B5%81"><span class="nav-text">4.1 执行流</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-%E5%BB%B6%E6%97%B6%E7%9A%84%E9%80%89%E6%8B%A9"><span class="nav-text">4.2 延时的选择</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E5%86%85%E6%A0%B8%E5%AE%9A%E6%97%B6%E5%99%A8"><span class="nav-text">三、内核定时器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%86%85%E6%A0%B8%E5%AE%9A%E6%97%B6%E5%99%A8%E7%AE%80%E4%BB%8B"><span class="nav-text">1. 内核定时器简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%B8%80%E4%B8%AA%E7%BB%93%E6%9E%84%E4%BD%93"><span class="nav-text">2. 一个结构体</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%9B%B8%E5%85%B3%E5%87%BD%E6%95%B0"><span class="nav-text">3. 相关函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-init-timer"><span class="nav-text">3.1 init_timer()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-add-timer"><span class="nav-text">3.2 add_timer()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-del-timer"><span class="nav-text">3.3 del_timer()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-mod-timer"><span class="nav-text">3.4 mod_timer()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5-del-timer-sync"><span class="nav-text">3.5 del_timer_sync()</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/382dea03.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV10-05-内核定时器-01-基础知识 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV10-05-内核定时器-01-基础知识
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-08 18:58:25" itemprop="dateCreated datePublished" datetime="2023-07-08T18:58:25+08:00">2023-07-08</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">LV10-驱动开发</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.1k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>15 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是内核定时器基础知识的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV10-05-%E5%86%85%E6%A0%B8%E5%AE%9A%E6%97%B6%E5%99%A8-01-%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center" width=150>Linux开发板</td>        <td align="left">华清远见 底板: FS4412_DEV_V5 核心板: FS4412 V2</td>      </tr>    <tr>        <td align="center" width=150>u-boot</td>        <td align="left">2013.01</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr><td align="center">文件</td><td align="center">下载链接</td></tr>    <tr><td align="left">---</td><td align="left"><a href="https://wwz.lanzouy.com/iH1vO09jxavi" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<h1 id="一、内核时间管理"><a href="#一、内核时间管理" class="headerlink" title="一、内核时间管理"></a><font size=3>一、内核时间管理</font></h1><h2 id="1-节拍率是什么？"><a href="#1-节拍率是什么？" class="headerlink" title="1. 节拍率是什么？"></a><font size=3>1. 节拍率是什么？</font></h2><p>Linux 内核中有大量的函数需要时间管理，比如周期性的调度程序、延时程序、对于我们驱动编写者来说最常用的定时器。硬件定时器提供时钟源，时钟源的频率可以设置， 设置好以后就周期性的产生定时中断，系统使用定时中断来计时。中断周期性产生的频率就是系统频率，也叫做<strong>节拍率</strong>(tick rate)(有的地方也叫系统频率)，比如 1000Hz， 100Hz 等等说的就是系统节拍率。系统节拍率是可以设置的，单位是 Hz，我们在编译 Linux 内核的时候可以通过图形化界面设置系统节拍率，按照如下路径打开配置界面：  </p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Kernel Features  ---&gt;</span><br><span class="line">	Timer frequency (100 Hz)  ---&gt;</span><br></pre></td></tr></table></figure>

<details class="folding-tag" blue><summary> 找不到怎么办？ </summary>
              <div class='content'>
              <p>反正我用的linux内核刚开始是找不到这个选项的，后来经过一番查探，发现，这种选项依赖于某些变量，我们直接在图形界面搜索 CONFIG_HZ 这个关键词（按下 &#x2F; ，然后输入名字即可搜索），会看到有么一个结果：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">这个是表示 HZ的默认值是200</span></span><br><span class="line">│ Symbol: HZ [=200]                                                       │  </span><br><span class="line">│ Type  : integer                                                         │  </span><br><span class="line">│   Defined at arch/arm/Kconfig:1678                                      |</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">后边还有几个与下边这类似的</span></span><br><span class="line">│ Symbol: HZ_100 [=n]                                                     │  </span><br><span class="line">│ Type  : boolean                                                         │  </span><br><span class="line">│ Prompt: 100 Hz                                                          │  </span><br><span class="line">│   Location:                                                             │  </span><br><span class="line">│ (2) -&gt; Kernel Features                                                  │  </span><br><span class="line">│       -&gt; Timer frequency (&lt;choice&gt; [=n])                                │  </span><br><span class="line">│   Defined at arch/arm/Kconfig:1658                                      │  </span><br><span class="line">│   Depends on: &lt;choice&gt;                                                  │  </span><br><span class="line"></span><br></pre></td></tr></table></figure><p>发现明明是有这个选项的，但是就是看不到，我们直接来到这个文件，打开：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim arch/arm/Kconfig +1658</span><br></pre></td></tr></table></figure><p>发现配置文件中有这么几行（前边是在文件中的行号）：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">1644 source kernel/Kconfig.preempt</span><br><span class="line">1645 </span><br><span class="line">1646 config HZ_FIXED</span><br><span class="line">1647         int</span><br><span class="line">1648         default 200 if ARCH_EBSA110 || ARCH_S3C24XX || ARCH_S5P64X0 || \</span><br><span class="line">1649                 ARCH_S5PV210 || ARCH_EXYNOS4</span><br><span class="line">1650         default AT91_TIMER_HZ if ARCH_AT91</span><br><span class="line">1651         default SHMOBILE_TIMER_HZ if ARCH_SHMOBILE_LEGACY</span><br><span class="line">1652         default 0</span><br><span class="line">1653 </span><br><span class="line">1654 choice</span><br><span class="line">1655         depends on HZ_FIXED = 0</span><br><span class="line">1656         prompt &quot;Timer frequency&quot;</span><br><span class="line">1657 </span><br><span class="line">1658 config HZ_100</span><br><span class="line">1659         bool &quot;100 Hz&quot;</span><br></pre></td></tr></table></figure><p>从这里得知，要保证 HZ_FIXED &#x3D; 0，才会有这些选项，所以后边知道怎么办啦，直接把 config HZ_FIXED下边的 default删掉，只留一个0，然后重新打开图形配置界面，就会发现，这个选项出来了。</p><p><strong>【注意事项】</strong>这里仅限于查看，看完记得改回来，我并不能保证改了之后会对内核编译的时候造成什么影响。</p>
              </div>
            </details>

<p>在Linux 内核会使用 CONFIG_HZ 来设置自己的系统时钟。我们打开 Linux 内核源码的这个文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">include/asm-generic/param.h</span><br></pre></td></tr></table></figure>

<p>  会看到有如下宏定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># <span class="keyword">undef</span> HZ</span></span><br><span class="line"><span class="meta"># <span class="keyword">define</span> HZ		CONFIG_HZ	<span class="comment">/* Internal kernel timer frequency */</span></span></span><br><span class="line"><span class="meta"># <span class="keyword">define</span> USER_HZ	100		<span class="comment">/* some user interfaces are */</span></span></span><br><span class="line"><span class="meta"># <span class="keyword">define</span> CLOCKS_PER_SEC	(USER_HZ)       <span class="comment">/* in &quot;ticks&quot; like times() */</span></span></span><br></pre></td></tr></table></figure>

<p>宏 HZ 就是 CONFIG_HZ，我们后面编写 Linux驱动的时候会常常用到 HZ，<strong>因为 HZ 表示一秒的节拍数，也就是频率</strong>。  </p>
<h2 id="2-节拍率的高低影响"><a href="#2-节拍率的高低影响" class="headerlink" title="2. 节拍率的高低影响"></a><font size=3>2. 节拍率的高低影响</font></h2><p>高节拍率会提高系统时间精度，如果采用 100Hz 的节拍率，时间精度就是 10ms，采用1000Hz 的话时间精度就是 1ms，精度提高了10 倍。高精度时钟的好处有很多，对于那些对时间要求严格的函数来说，能够以更高的精度运行，时间测量也更加准确。</p>
<p>高节拍率会<strong>导致中断的产生更加频繁</strong>，频繁的中断会加剧系统的负担， 1000Hz 和 100Hz的系统节拍率相比，系统要花费 10 倍的“精力”去处理中断。中断服务函数占用处理器的时间增加，但是现在的处理器性能都很强大，所以采用 1000Hz 的系统节拍率并不会增加太大的负载压力。根据自己的实际情况，选择合适的系统节拍率。  </p>
<h2 id="3-jiffies"><a href="#3-jiffies" class="headerlink" title="3. jiffies"></a><font size=3>3. jiffies</font></h2><p>Linux 内核使用全局变量 jiffies 来记录系统从启动以来的系统节拍数，系统启动的时候会将 jiffies 初始化为 0，这个变量定义在 linux内核源码的这个文件中：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">include/linux/jiffies.h</span><br></pre></td></tr></table></figure>

<p>我们打开这个文件，可以看到如下定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * The 64-bit value is not atomic - you MUST NOT read it</span></span><br><span class="line"><span class="comment"> * without sampling the sequence number in jiffies_lock.</span></span><br><span class="line"><span class="comment"> * get_jiffies_64() will do this for you as appropriate.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">extern</span> u64 __jiffy_data jiffies_64;</span><br><span class="line"><span class="keyword">extern</span> <span class="type">unsigned</span> <span class="type">long</span> <span class="keyword">volatile</span> __jiffy_data jiffies;</span><br></pre></td></tr></table></figure>

<p>jiffies_64 和 jiffies 其实是同一个东西， jiffies_64 用于 64 位系统，而 jiffies 用于 32 位系统。为了兼容不同的硬件， jiffies 其实就是 jiffies_64 的低 32 位， jiffies_64 和 jiffies 的结构如下图：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV10-05-%E5%86%85%E6%A0%B8%E5%AE%9A%E6%97%B6%E5%99%A8-01-%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/img/image-20220918154908163.png" alt="image-20220918154908163" style="zoom:50%;" />

<p>当我们访问 jiffies 的时候其实访问的是 jiffies_64 的低 32 位，使用 get_jiffies_64 这个函数可以获取 jiffies_64 的值。在 32 位的系统上读取 jiffies 的值，在 64 位的系统上 jiffes 和 jiffies_64 表示同一个变量，因此也可以直接读取 jiffies 的值。所以不管是 32 位的系统还是 64 位系统，都可以使用 jiffies。  </p>
<p>前面说 HZ 表示每秒的节拍数， jiffies 表示系统运行的 jiffies 节拍数，所以 jiffies &#x2F; HZ 就是系统运行时间，单位为秒。不管是 32 位还是 64 位的 jiffies，都有溢出的风险，溢出以后会重新从 0 开始计数，相当于绕回来了，因此有的地方也将这个现象也叫做绕回。假如 HZ 为最大值 1000 的时候， 32 位的 jiffies 只需要 49.7 天就发生了绕回，对于 64 位的 jiffies 来说大概需要 5.8 亿年才能绕回，因此 jiffies_64 的绕回忽略不计，所以处理 32 位 jiffies 的绕回显得尤为重要。</p>
<p>Linux 内核提供了几个 API 函数来处理绕回，这些函数定义在linux内核源码的这个文件中：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">include/linux/jiffies.h</span><br></pre></td></tr></table></figure>

<p>我们打开文件，会看到有如下相关函数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> *      These inlines deal with timer wrapping correctly. You are </span></span><br><span class="line"><span class="comment"> *      strongly encouraged to use them</span></span><br><span class="line"><span class="comment"> *      1. Because people otherwise forget</span></span><br><span class="line"><span class="comment"> *      2. Because if the timer wrap changes in future you won&#x27;t have to</span></span><br><span class="line"><span class="comment"> *         alter your driver code.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * time_after(a,b) returns true if the time a is after time b.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Do this with &quot;&lt;0&quot; and &quot;&gt;=0&quot; to only test the sign of the result. A</span></span><br><span class="line"><span class="comment"> * good compiler would generate better code (and a really good compiler</span></span><br><span class="line"><span class="comment"> * wouldn&#x27;t care). Gcc is currently neither.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> time_after(a,b)         \</span></span><br><span class="line"><span class="meta">        (typecheck(unsigned long, a) &amp;&amp; \</span></span><br><span class="line"><span class="meta">         typecheck(unsigned long, b) &amp;&amp; \</span></span><br><span class="line"><span class="meta">         ((long)((b) - (a)) &lt; 0))</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> time_before(a,b)        time_after(b,a)</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> time_after_eq(a,b)      \</span></span><br><span class="line"><span class="meta">        (typecheck(unsigned long, a) &amp;&amp; \</span></span><br><span class="line"><span class="meta">         typecheck(unsigned long, b) &amp;&amp; \</span></span><br><span class="line"><span class="meta">         ((long)((a) - (b)) &gt;= 0))</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> time_before_eq(a,b)     time_after_eq(b,a)</span></span><br></pre></td></tr></table></figure>

<p>如果 a 超过 b 的话， time_after 函数返回真，否则返回假。如果 a 没有超过 b 的话 time_before 函数返回真，否则返回假。time_after_eq 函数和 time_after 函数类似，只是多了判断等于这个条件。同理， time_before_eq 函数和 time_before 函数也类似。  </p>
<h2 id="4-代码执行超时判断"><a href="#4-代码执行超时判断" class="headerlink" title="4. 代码执行超时判断"></a><font size=3>4. 代码执行超时判断</font></h2><p>上边了解了<code>jiffies</code>，我们可以用它来判断某段程序有没有执行超时：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">unsigned</span> <span class="type">long</span> timeout;</span><br><span class="line">timeout = jiffies + (<span class="number">2</span> * HZ); <span class="comment">/* 超时的时间点,这里是2s */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*************************************</span></span><br><span class="line"><span class="comment"> *           具体的代码</span></span><br><span class="line"><span class="comment"> *************************************/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 判断有没有超时 */</span></span><br><span class="line"><span class="keyword">if</span>(time_before(jiffies, timeout))</span><br><span class="line">&#123;</span><br><span class="line">	<span class="comment">/* 超时未发生 */</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="comment">/* 超时发生 */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="二、延时机制"><a href="#二、延时机制" class="headerlink" title="二、延时机制"></a><font size=3>二、延时机制</font></h1><p>在linux中，根据延时时间长短可以有短延时和长延时，按照延时方式，可以分为阻塞延时和非阻塞延时（忙等待）。</p>
<h2 id="1-忙等待的短延迟"><a href="#1-忙等待的短延迟" class="headerlink" title="1. 忙等待的短延迟"></a><font size=3>1. 忙等待的短延迟</font></h2><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> <span class="type">void</span> <span class="title function_">ndelay</span><span class="params">(<span class="type">unsigned</span> <span class="type">long</span> nsecs)</span></span><br><span class="line">2. <span class="type">void</span> <span class="title function_">udelay</span><span class="params">(<span class="type">unsigned</span> <span class="type">long</span> usecs)</span></span><br><span class="line">3. <span class="type">void</span> <span class="title function_">mdelay</span><span class="params">(<span class="type">unsigned</span> <span class="type">long</span> msecs)</span></span><br></pre></td></tr></table></figure>

<p>实际上是在函数内不进行循环，不会睡眠。</p>
<h2 id="2-忙等待的长延时"><a href="#2-忙等待的长延时" class="headerlink" title="2. 忙等待的长延时"></a><font size=3>2. 忙等待的长延时</font></h2><p>使用 jiffies 相关比较宏来实现，它也是在函数里边进行循环，不会睡眠：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">time_after(a,b)    <span class="comment">// a &gt; b</span></span><br><span class="line">time_before(a,b)   <span class="comment">// a &lt; b</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 延迟100个 jiffies</span></span><br><span class="line"><span class="type">unsigned</span> <span class="type">long</span> delay = jiffies + <span class="number">100</span>;</span><br><span class="line"><span class="keyword">while</span>(time_before(jiffies,delay))</span><br><span class="line">&#123;</span><br><span class="line">    ;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 延迟 2s</span></span><br><span class="line"><span class="type">unsigned</span> <span class="type">long</span> delay = jiffies + <span class="number">2</span>*HZ;</span><br><span class="line"><span class="keyword">while</span>(time_before(jiffies,delay))</span><br><span class="line">&#123;</span><br><span class="line">    ;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-睡眠延时"><a href="#3-睡眠延时" class="headerlink" title="3. 睡眠延时"></a><font size=3>3. 睡眠延时</font></h2><p>这个属于阻塞类延时，开始延时后，进程阻塞，让出CPU。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">msleep</span><span class="params">(<span class="type">unsigned</span> <span class="type">int</span> msecs)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">unsigned</span> <span class="type">long</span> <span class="title function_">msleep_interruptible</span><span class="params">(<span class="type">unsigned</span> <span class="type">int</span> msecs)</span>;</span><br></pre></td></tr></table></figure>

<h2 id="4-延时机制的选择"><a href="#4-延时机制的选择" class="headerlink" title="4. 延时机制的选择"></a><font size=3>4. 延时机制的选择</font></h2><h3 id="4-1-执行流"><a href="#4-1-执行流" class="headerlink" title="4.1 执行流"></a><font size=3>4.1 执行流</font></h3><p>执行流：有开始有结束总体顺序执行的一段独立代码，又被称为<strong>代码上下文</strong> 。计算机系统中的执行流的分类：</p>
<ul>
<li>任务流——任务上下文（都参与CPU时间片轮转，都有任务的五种状态：就绪态  运行态  睡眠态  僵死态  暂停态）</li>
</ul>
<p>（1）进程</p>
<p>（2）线程</p>
<p>内核线程：内核创建的线程。</p>
<p>应用线程：应用进程创建的线程。</p>
<ul>
<li>异常流——异常上下文</li>
</ul>
<p>（1）中断</p>
<p>（2）其他异常</p>
<blockquote>
<p>应用编程可能涉及到的执行流：</p>
<p>（1）进程</p>
<p>（2）线程</p>
</blockquote>
<blockquote>
<p>内核编程可能涉及到的执行流：</p>
<p>（1）应用程序自身代码运行在用户空间，处于用户态—— 用户态 app</p>
<p>（2）应用程序正在调用系统调用函数，运行在内核空间，处于内核态，即代码是内核代码但处于应用执行流（即属于一个应用进程或应用线程）——内核态 app</p>
<p>（3）一直运行于内核空间，处于内核态，属于内核内的任务上下文—— 内核线程</p>
<p>（4）一直运行于内核空间，处于内核态，专门用来处理各种异常—— 异常上下文</p>
</blockquote>
<h3 id="4-2-延时的选择"><a href="#4-2-延时的选择" class="headerlink" title="4.2 延时的选择"></a><font size=3>4.2 延时的选择</font></h3><p>延时机制的选择原则：</p>
<ul>
<li><p>任务上下文短延迟采用忙等待类，长延迟采用阻塞类</p>
</li>
<li><p>异常上下文中只能采用忙等待类</p>
</li>
</ul>
<h1 id="三、内核定时器"><a href="#三、内核定时器" class="headerlink" title="三、内核定时器"></a><font size=3>三、内核定时器</font></h1><h2 id="1-内核定时器简介"><a href="#1-内核定时器简介" class="headerlink" title="1. 内核定时器简介"></a><font size=3>1. 内核定时器简介</font></h2><p>定时器是一个很常用的功能，需要周期性处理的工作都要用到定时器， Linux 内核采用系统时钟来实现了一个定时器。 Linux 内核定时器使用很简单，只需要提供超时时间（相当于定时值）和定时处理函数即可，当超时时间到了以后设置的定时处理函数就会执行，和我们使用硬件定时器的套路一样，只是使用内核定时器不需要做一大堆的寄存器初始化工作。</p>
<p>在使用内核定时器的时候要注意一点，<strong>内核定时器并不是周期性运行的，超时以后就会自动关闭</strong>，因此如果想要实现周期性定时，那么就需要在定时处理函数中重新开启定时器。   </p>
<h2 id="2-一个结构体"><a href="#2-一个结构体" class="headerlink" title="2. 一个结构体"></a><font size=3>2. 一个结构体</font></h2><p>Linux 内核使用 timer_list 结构体表示内核定时器 ，这个结构体定义在linux内核源码的这个文件中：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">include/linux/timer.h </span><br></pre></td></tr></table></figure>

<p>我们打开这个文件，会看到结构体定义如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">timer_list</span> &#123;</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * All fields that change during normal runtime grouped to the</span></span><br><span class="line"><span class="comment">         * same cacheline</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="class"><span class="keyword">struct</span> <span class="title">list_head</span> <span class="title">entry</span>;</span></span><br><span class="line">        <span class="type">unsigned</span> <span class="type">long</span> expires;</span><br><span class="line">        <span class="class"><span class="keyword">struct</span> <span class="title">tvec_base</span> *<span class="title">base</span>;</span></span><br><span class="line"></span><br><span class="line">        <span class="type">void</span> (*function)(<span class="type">unsigned</span> <span class="type">long</span>);</span><br><span class="line">        <span class="type">unsigned</span> <span class="type">long</span> data;</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> slack;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">ifdef</span> CONFIG_TIMER_STATS</span></span><br><span class="line">        <span class="type">int</span> start_pid;</span><br><span class="line">        <span class="type">void</span> *start_site;</span><br><span class="line">        <span class="type">char</span> start_comm[<span class="number">16</span>];</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">ifdef</span> CONFIG_LOCKDEP</span></span><br><span class="line">        <span class="class"><span class="keyword">struct</span> <span class="title">lockdep_map</span> <span class="title">lockdep_map</span>;</span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>【成员介绍】</strong></p>
<ul>
<li>expires：unsigned long 类型，定时器的超时时间，单位是节拍数，也就是 jiffies + x * HZ，其中 x 就表示我们要定时的秒数。</li>
<li>function：函数指针，时间到达后，执行的回调函数，这是一个软中断异常上下文。</li>
<li>data：unsigned long 类型，表示要传递给回调函数的参数。</li>
</ul>
<h2 id="3-相关函数"><a href="#3-相关函数" class="headerlink" title="3. 相关函数"></a><font size=3>3. 相关函数</font></h2><h3 id="3-1-init-timer"><a href="#3-1-init-timer" class="headerlink" title="3.1 init_timer()"></a><font size=3>3.1 <code>init_timer()</code></font></h3><p>我们使用以下命令查询一下函数所在头文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">grep init_timer -r -n ~/5linux/linux-3.14/include</span><br></pre></td></tr></table></figure>

<p>经过查找，我们可以得到如下信息：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/timer.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> init_timer(timer)                                               \</span></span><br><span class="line"><span class="meta">        __init_timer((timer), 0)</span></span><br><span class="line"><span class="comment">// __init_timer的定义</span></span><br><span class="line"><span class="meta">#<span class="keyword">ifdef</span> CONFIG_LOCKDEP</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __init_timer(_timer, _flags)                                    \</span></span><br><span class="line"><span class="meta">        do &#123;                                                            \</span></span><br><span class="line"><span class="meta">                static struct lock_class_key __key;                     \</span></span><br><span class="line"><span class="meta">                init_timer_key((_timer), (_flags), #_timer, &amp;__key);    \</span></span><br><span class="line"><span class="meta">        &#125; while (0)</span></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"><span class="meta">#<span class="keyword">else</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __init_timer(_timer, _flags)                                    \</span></span><br><span class="line"><span class="meta">        init_timer_key((_timer), (_flags), NULL, NULL)</span></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"><span class="comment">// init_timer_key的定义</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">init_timer_key</span><span class="params">(<span class="keyword">struct</span> timer_list *timer, <span class="type">unsigned</span> <span class="type">int</span> flags,</span></span><br><span class="line"><span class="params">                    <span class="type">const</span> <span class="type">char</span> *name, <span class="keyword">struct</span> lock_class_key *key)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数其实是一个宏，用于初始化一个定时器，实际上就是初始化定义好了的 timer_list 变量  。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>timer：struct timer_list *类型，表示要初始化的定时器。</li>
</ul>
<p><strong>【返回值】</strong>none</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none</p>
<h3 id="3-2-add-timer"><a href="#3-2-add-timer" class="headerlink" title="3.2 add_timer()"></a><font size=3>3.2 <code>add_timer()</code></font></h3><p>我们使用以下命令查询一下函数所在头文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">grep add_timer -r -n ~/5linux/linux-3.14/include</span><br></pre></td></tr></table></figure>

<p>经过查找，我们可以得到如下信息：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/timer.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="keyword">extern</span> <span class="type">void</span> <span class="title function_">add_timer</span><span class="params">(<span class="keyword">struct</span> timer_list *timer)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于向内核注册一个定时器。  </p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>timer：struct timer_list *类型，表示要注册的定时器。</li>
</ul>
<p><strong>【返回值】</strong>none</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none</p>
<h3 id="3-3-del-timer"><a href="#3-3-del-timer" class="headerlink" title="3.3 del_timer()"></a><font size=3>3.3 <code>del_timer()</code></font></h3><p>我们使用以下命令查询一下函数所在头文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">grep del_timer -r -n ~/5linux/linux-3.14/include</span><br></pre></td></tr></table></figure>

<p>经过查找，我们可以得到如下信息：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/timer.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="keyword">extern</span> <span class="type">int</span> <span class="title function_">del_timer</span><span class="params">(<span class="keyword">struct</span> timer_list * timer)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于删除一个定时器，不管定时器有没有被激活，都可以使用此函数删除。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>timer：struct timer_list *类型，表示要删除的定时器。</li>
</ul>
<p><strong>【返回值】</strong>int 类型，返回0表示定时器还没被激活，返回 1表示定时器已经激活。  </p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>在多处理器系统上，定时器可能会在其他的处理器上运行，因此在调用 del_timer 函数删除定时器之前要先等待其他处理器的定时处理器函数退出。  </p>
<h3 id="3-4-mod-timer"><a href="#3-4-mod-timer" class="headerlink" title="3.4 mod_timer()"></a><font size=3>3.4 <code>mod_timer()</code></font></h3><p>我们使用以下命令查询一下函数所在头文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">grep mod_timer -r -n ~/5linux/linux-3.14/include</span><br></pre></td></tr></table></figure>

<p>经过查找，我们可以得到如下信息：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/timer.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="keyword">extern</span> <span class="type">int</span> <span class="title function_">mod_timer</span><span class="params">(<span class="keyword">struct</span> timer_list *timer, <span class="type">unsigned</span> <span class="type">long</span> expires)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于修改定时器的值，如果定时器还没有激活的话， mod_timer 函数会激活定时器 。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>timer：struct timer_list * 类型，表示要修改的定时器。</li>
<li>expires：unsigned long 类型，修改后的超时时间，单位为节拍数，格式为 jiffies + x * HZ。</li>
</ul>
<p><strong>【返回值】</strong>int 类型，返回0表示调用 mod_timer 函数前定时器未被激活，返回1表示调用 mod_timer 函数前定时器已被激活。  </p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none  </p>
<h3 id="3-5-del-timer-sync"><a href="#3-5-del-timer-sync" class="headerlink" title="3.5 del_timer_sync()"></a><font size=3>3.5 <code>del_timer_sync()</code></font></h3><p>我们使用以下命令查询一下函数所在头文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">grep del_timer_sync -r -n ~/5linux/linux-3.14/include</span><br></pre></td></tr></table></figure>

<p>经过查找，我们可以得到如下信息：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/timer.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="keyword">extern</span> <span class="type">int</span> <span class="title function_">del_timer_sync</span><span class="params">(<span class="keyword">struct</span> timer_list *timer)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于删除一个定时器，会等待其他处理器使用完定时器再删除。 </p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>timer：struct timer_list * 类型，表示要删除的定时器。</li>
</ul>
<p><strong>【返回值】</strong>int 类型，返回 0 表示定时器未被激活，返回 1 表示定时器已被激活。  </p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>del_timer_sync 不能使用在中断上下文中。  </p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/382dea03.html">LV10-05-内核定时器-01-基础知识</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月08日 - 18:58</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/382dea03.html" title="LV10-05-内核定时器-01-基础知识">https://sumumm.github.io/post/382dea03.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/" rel="tag"><i class="fa fa-tag"></i> LV10-驱动开发</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/7b1a8f39.html" rel="prev" title="LV10-06-内核内存管理-01-基础知识">
                  <i class="fa fa-angle-left"></i> LV10-06-内核内存管理-01-基础知识
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/cffac5d7.html" rel="next" title="LV10-04-并发与竞争-02-并发控制机制">
                  LV10-04-并发与竞争-02-并发控制机制 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
